﻿////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  © 2012 Stanislav S. Yarmonov.
//
//  TODO:LICENSE
//     
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Web;

namespace Pandora.Web
{
    ////////////////////////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Cookies collection extensions.
    /// </summary>
    ////////////////////////////////////////////////////////////////////////////////////////////////
    public static class HttpCookieCollectionExtensions
    {
        ////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Update cookie.
        /// </summary>
        /// <param name="cookies">
        /// Cookies collection.
        /// </param>
        /// <param name="name">
        /// Name of the cookie to be updated.
        /// </param>
        /// <param name="value">
        /// New cookie value.
        /// </param>
        /// <param name="expires">
        /// The time span when cookie wil expire.
        /// </param>
        /// <returns>
        /// Returns cookie collection for fluent coding.
        /// </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////
        public static HttpCookieCollection Update(
            this HttpCookieCollection cookies,
            string name,
            string value,
            TimeSpan expires
        )
        {
            HttpContext context = HttpContext.Current;
            HttpCookie cookie = context.Request.Cookies[name];

            if (cookie != null)
            {
                cookie.Expires = new DateTime(1999, 1, 1);
                context.Response.Cookies.Remove(name);
                context.Response.Cookies.Add(cookie);
            }

            cookie = new HttpCookie(name);
            cookie.Expires = DateTime.Now.Add(expires);
            cookie.Value = value;
            context.Response.Cookies.Add(cookie);

            return cookies;
        }
    }
}
